package com.hwg.emp.common.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.UUID;

/**
 * 数据库连接工具类
 * @author Here We Go
 *
 */
public class DBUtil {
	private static String URL = null;
	
	private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<Connection>();
	static {
		init();
	}

	private static void init() {
		try {
			//读取配置文件
			System.getProperties().load(DBUtil.class.getResourceAsStream("/db.ini"));
			//获取url
			URL=System.getProperty("URL");
			//加载驱动 System.getProperty第一个参数为属性名，第二个参数为默认值(没有找到此属性是执行的值)
			Class.forName(System.getProperty("DRIVER","com.mysql.jdbc.Driver"));

		} catch (Exception e) {
			
			throw new RuntimeException("无法加载驱动",e);
		}
	}

	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection() throws SQLException {
		Connection connection = THREAD_LOCAL.get();
		if (connection == null || connection.isClosed()) {
			connection = DriverManager.getConnection(URL,"root","123");
			THREAD_LOCAL.set(connection);
		}
		return connection;
	}

	/**
	 * 关闭数据库连接
	 */
	public static void closeConnection() {
		try {
			Connection connection = THREAD_LOCAL.get();
			if (connection != null) {
				connection.close();
				THREAD_LOCAL.remove();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void beginTranscation()throws SQLException {
		Connection connection =getConnection();
		connection.setAutoCommit(false);
	}

	public static void commitTranscation()throws SQLException  {
		getConnection().commit();
	}

	public static void rollbackTranscation()throws SQLException  {
		getConnection().rollback();
	}

	public static String uuid() {
		String uuid = UUID.randomUUID().toString();
		char[] cs = new char[32];
		for (int i = uuid.length(), j = 0; i-- > 0;) {
			if (uuid.charAt(i) != '-') {
				cs[j++] = uuid.charAt(i);
			}
		}
		return new String(cs);
	}
}
